
package com.scalar.chiptrack.users.actions;

import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.users.forms.ChangePasswordForm;
import com.scalar.chiptrack.utils.MessageDigestUtils;
import com.scalar.chiptrack.utils.StringUtils;


public class ChangePasswordAction extends ChipTrackAction {

    
    public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response) 
                                      throws Exception {
        User user = null;
        String action = request.getParameter ("action");
        
        HashMap info = new HashMap();
        request.setAttribute (SessionKeys.INFO_MESSAGES, info);
        
        HashMap errors = new HashMap();
        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
        
        HttpSession session = request.getSession();
        if ((session == null) || ((user = (User) session.getAttribute (SessionKeys.USER_KEY)) == null)) {
            errors.put ("User is not logged in", null);
            return (mapping.findForward ("failure"));
        }
        
        ChangePasswordForm changePasswordForm = (ChangePasswordForm) form;
        changePasswordForm.setUserId (user.getUserId());
        request.setAttribute ("changePasswordForm", changePasswordForm);
        
        // UPDATE
        if ("update".equalsIgnoreCase(action) == true) {

            HashMap formErrors = validateForm (changePasswordForm);
            if ((formErrors != null) && (formErrors.isEmpty() == false)) {
                request.setAttribute (SessionKeys.ERROR_MESSAGES, formErrors);
                System.out.println (formErrors);
                return (mapping.findForward ("failure"));
            }

            //System.out.println ("userID: " + user.getUserId() + ", old pass: " + changePasswordForm.getOldPassword() + ", new pass: " + changePasswordForm.getNewPassword());
            try {
                UserDAO.changePassword (null /*dbTransaction*/, user.getUserId(), changePasswordForm.getOldPassword(), StringUtils.concatBytes (MessageDigestUtils.getMAC (changePasswordForm.getNewPassword()), ","));
                info.put ("Password has been changed successfully", null);
            }
            catch (ScalarException se) {
                
                if (se.getMessage().indexOf ("Password mismatch") != -1) {
                    errors.put ("Incorrect old password", null);
                }
                else {
                    errors.put ("Internal Server Error", "Could not change the password");
                    se.printStackTrace();
                }
            }

            return (mapping.findForward ("success"));
        }
        
        
        // VIEW
        // Nothing much to do here... send directly to the page
        return (mapping.findForward ("success"));
    }
    
    
    private HashMap validateForm (ChangePasswordForm changePasswordForm) {
                
        HashMap errors = new LinkedHashMap();
        
        String oldPassword = changePasswordForm.getOldPassword();
        String password = changePasswordForm.getNewPassword();
        String password1 = changePasswordForm.getNewPassword1();       

        if ((oldPassword == null) || (oldPassword.trim().length() == 0)) {
            errors.put ("Old Password", "Please Enter Old Password ");
        }
        
        if ((password == null) || (password.trim().length() == 0)) {
            errors.put ("Password", "Please Enter New Password ");
        }
        
        if ((password != null) && (password.equals (password1) == false)) {
            errors.put ("Password", "Password did not match");
        }
                
        return errors;
    }
}
